<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>健康检查 - RustCloud 仪表板</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background-color: #f5f5f5;
            color: #333;
        }

        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px 0;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 0 20px;
        }

        .header h1 {
            font-size: 28px;
            font-weight: 600;
        }

        .nav {
            background: white;
            padding: 15px 0;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
            margin-bottom: 30px;
        }

        .nav ul {
            list-style: none;
            display: flex;
            gap: 30px;
        }

        .nav a {
            text-decoration: none;
            color: #333;
            font-weight: 500;
            padding: 10px 15px;
            border-radius: 5px;
            transition: background-color 0.3s;
        }

        .nav a:hover, .nav a.active {
            background-color: #667eea;
            color: white;
        }

        .health-overview {
            background: white;
            border-radius: 10px;
            padding: 30px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            margin-bottom: 30px;
            text-align: center;
        }

        .overall-status {
            font-size: 48px;
            margin-bottom: 15px;
        }

        .status-healthy { color: #10b981; }
        .status-warning { color: #f59e0b; }
        .status-error { color: #ef4444; }
        .status-critical { color: #dc2626; }

        .status-text {
            font-size: 24px;
            font-weight: 600;
            margin-bottom: 10px;
        }

        .status-description {
            color: #666;
            font-size: 16px;
        }

        .health-metrics {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }

        .metric-card {
            background: white;
            border-radius: 10px;
            padding: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }

        .metric-title {
            color: #667eea;
            font-size: 14px;
            font-weight: 600;
            margin-bottom: 15px;
            text-transform: uppercase;
        }

        .metric-value {
            font-size: 36px;
            font-weight: bold;
            margin-bottom: 8px;
        }

        .metric-unit {
            font-size: 14px;
            color: #666;
        }

        .progress-bar {
            width: 100%;
            height: 8px;
            background: #e1e5e9;
            border-radius: 4px;
            overflow: hidden;
            margin-top: 10px;
        }

        .progress-fill {
            height: 100%;
            transition: width 0.5s ease;
        }

        .progress-good { background: #10b981; }
        .progress-warning { background: #f59e0b; }
        .progress-danger { background: #ef4444; }

        .services-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: 20px;
        }

        .service-card {
            background: white;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            overflow: hidden;
        }

        .service-header {
            padding: 20px;
            border-bottom: 1px solid #e1e5e9;
        }

        .service-name {
            font-size: 18px;
            font-weight: 600;
            margin-bottom: 5px;
        }

        .service-status {
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .status-indicator {
            width: 12px;
            height: 12px;
            border-radius: 50%;
        }

        .status-indicator.healthy { background: #10b981; }
        .status-indicator.warning { background: #f59e0b; }
        .status-indicator.error { background: #ef4444; }
        .status-indicator.unknown { background: #6b7280; }

        .service-details {
            padding: 20px;
        }

        .service-metric {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 12px;
        }

        .service-metric:last-child {
            margin-bottom: 0;
        }

        .metric-label {
            color: #666;
            font-size: 14px;
        }

        .metric-value-small {
            font-weight: 600;
        }

        .refresh-button {
            background: #667eea;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 5px;
            cursor: pointer;
            margin-bottom: 20px;
            transition: background-color 0.3s;
        }

        .refresh-button:hover {
            background: #5a67d8;
        }

        .loading {
            text-align: center;
            padding: 40px;
            color: #666;
        }

        .error-message {
            background: #fef2f2;
            border: 1px solid #fecaca;
            color: #dc2626;
            padding: 15px;
            border-radius: 5px;
            margin-bottom: 20px;
        }

        .uptime-badge {
            display: inline-block;
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 12px;
            font-weight: bold;
        }

        .uptime-excellent {
            background: #d1fae5;
            color: #065f46;
        }

        .uptime-good {
            background: #fef3c7;
            color: #92400e;
        }

        .uptime-poor {
            background: #fee2e2;
            color: #991b1b;
        }

        .timestamp {
            text-align: center;
            color: #666;
            font-size: 12px;
            margin-top: 20px;
        }
    </style>
</head>
<body>
    <header class="header">
        <div class="container">
            <h1>💗 健康检查</h1>
        </div>
    </header>

    <nav class="nav">
        <div class="container">
            <ul>
                <li><a href="/">概览</a></li>
                <li><a href="/metrics">指标</a></li>
                <li><a href="/alerts">告警</a></li>
                <li><a href="/apm">APM</a></li>
                <li><a href="/health" class="active">健康检查</a></li>
            </ul>
        </div>
    </nav>

    <main class="container">
        <!-- 整体健康状态 -->
        <div class="health-overview">
            <div class="overall-status status-healthy" id="overall-status">✅</div>
            <div class="status-text" id="status-text">系统运行正常</div>
            <div class="status-description" id="status-description">所有核心服务正常运行</div>
        </div>

        <button class="refresh-button" onclick="loadHealthData()">🔄 刷新健康状态</button>

        <div id="error-container"></div>

        <!-- 系统指标 -->
        <div class="health-metrics">
            <div class="metric-card">
                <div class="metric-title">CPU 使用率</div>
                <div class="metric-value status-healthy" id="cpu-usage">-</div>
                <div class="metric-unit">%</div>
                <div class="progress-bar">
                    <div class="progress-fill progress-good" id="cpu-progress" style="width: 0%;"></div>
                </div>
            </div>

            <div class="metric-card">
                <div class="metric-title">内存使用率</div>
                <div class="metric-value status-healthy" id="memory-usage">-</div>
                <div class="metric-unit">%</div>
                <div class="progress-bar">
                    <div class="progress-fill progress-good" id="memory-progress" style="width: 0%;"></div>
                </div>
            </div>

            <div class="metric-card">
                <div class="metric-title">磁盘使用率</div>
                <div class="metric-value status-healthy" id="disk-usage">-</div>
                <div class="metric-unit">%</div>
                <div class="progress-bar">
                    <div class="progress-fill progress-good" id="disk-progress" style="width: 0%;"></div>
                </div>
            </div>

            <div class="metric-card">
                <div class="metric-title">网络延迟</div>
                <div class="metric-value status-healthy" id="network-latency">-</div>
                <div class="metric-unit">ms</div>
            </div>
        </div>

        <!-- 服务健康状态 -->
        <h2 style="margin-bottom: 20px;">服务健康状态</h2>
        <div class="services-grid" id="services-container">
            <div class="loading">正在检查服务状态...</div>
        </div>

        <div class="timestamp" id="last-update">
            最后更新时间: -
        </div>
    </main>

    <script>
        let healthData = null;

        // 模拟系统指标数据
        const mockSystemMetrics = {
            cpu_usage: Math.random() * 30 + 10,      // 10-40%
            memory_usage: Math.random() * 25 + 20,   // 20-45%
            disk_usage: Math.random() * 20 + 30,     // 30-50%
            network_latency: Math.random() * 10 + 5   // 5-15ms
        };

        // 模拟服务数据
        const mockServices = [
            {
                name: "用户服务",
                status: "healthy",
                uptime: 99.9,
                response_time: 45,
                error_rate: 0.1,
                version: "1.2.3"
            },
            {
                name: "订单服务", 
                status: "healthy",
                uptime: 99.5,
                response_time: 67,
                error_rate: 0.3,
                version: "2.1.0"
            },
            {
                name: "支付服务",
                status: "warning",
                uptime: 98.9,
                response_time: 120,
                error_rate: 1.2,
                version: "1.5.4"
            },
            {
                name: "通知服务",
                status: "healthy",
                uptime: 99.8,
                response_time: 23,
                error_rate: 0.05,
                version: "1.0.1"
            }
        ];

        // 加载健康数据
        async function loadHealthData() {
            try {
                showLoading();
                
                // 尝试从 API 获取真实数据
                try {
                    const response = await fetch('/api/health');
                    const result = await response.json();
                    
                    if (result.success) {
                        healthData = result.data;
                    }
                } catch (apiError) {
                    console.log('使用模拟数据，API 不可用');
                }
                
                // 更新系统指标（使用模拟数据）
                updateSystemMetrics();
                
                // 更新服务状态（使用模拟数据）
                updateServices();
                
                // 更新整体状态
                updateOverallStatus();
                
                hideError();
            } catch (error) {
                console.error('加载健康数据失败:', error);
                showError('无法获取健康状态');
            }
        }

        // 更新系统指标
        function updateSystemMetrics() {
            // CPU 使用率
            const cpuUsage = mockSystemMetrics.cpu_usage;
            document.getElementById('cpu-usage').textContent = cpuUsage.toFixed(1);
            updateProgressBar('cpu-progress', cpuUsage, 60, 80);
            updateMetricColor('cpu-usage', cpuUsage, 60, 80);

            // 内存使用率
            const memoryUsage = mockSystemMetrics.memory_usage;
            document.getElementById('memory-usage').textContent = memoryUsage.toFixed(1);
            updateProgressBar('memory-progress', memoryUsage, 70, 85);
            updateMetricColor('memory-usage', memoryUsage, 70, 85);

            // 磁盘使用率
            const diskUsage = mockSystemMetrics.disk_usage;
            document.getElementById('disk-usage').textContent = diskUsage.toFixed(1);
            updateProgressBar('disk-progress', diskUsage, 80, 90);
            updateMetricColor('disk-usage', diskUsage, 80, 90);

            // 网络延迟
            const networkLatency = mockSystemMetrics.network_latency;
            document.getElementById('network-latency').textContent = networkLatency.toFixed(1);
            updateMetricColor('network-latency', networkLatency, 50, 100);
        }

        // 更新进度条
        function updateProgressBar(elementId, value, warningThreshold, dangerThreshold) {
            const progressBar = document.getElementById(elementId);
            progressBar.style.width = Math.min(value, 100) + '%';
            
            // 更新颜色
            progressBar.className = 'progress-fill ';
            if (value < warningThreshold) {
                progressBar.className += 'progress-good';
            } else if (value < dangerThreshold) {
                progressBar.className += 'progress-warning';
            } else {
                progressBar.className += 'progress-danger';
            }
        }

        // 更新指标颜色
        function updateMetricColor(elementId, value, warningThreshold, dangerThreshold) {
            const element = document.getElementById(elementId);
            element.className = 'metric-value ';
            
            if (value < warningThreshold) {
                element.className += 'status-healthy';
            } else if (value < dangerThreshold) {
                element.className += 'status-warning';
            } else {
                element.className += 'status-error';
            }
        }

        // 更新服务状态
        function updateServices() {
            const container = document.getElementById('services-container');
            
            container.innerHTML = mockServices.map(service => {
                const uptimeBadge = getUptimeBadge(service.uptime);
                
                return `
                    <div class="service-card">
                        <div class="service-header">
                            <div class="service-name">${service.name}</div>
                            <div class="service-status">
                                <span class="status-indicator ${service.status}"></span>
                                <span>${getStatusText(service.status)}</span>
                            </div>
                        </div>
                        <div class="service-details">
                            <div class="service-metric">
                                <span class="metric-label">运行时间:</span>
                                <span class="metric-value-small ${uptimeBadge.class}">${service.uptime}%</span>
                            </div>
                            <div class="service-metric">
                                <span class="metric-label">响应时间:</span>
                                <span class="metric-value-small">${service.response_time}ms</span>
                            </div>
                            <div class="service-metric">
                                <span class="metric-label">错误率:</span>
                                <span class="metric-value-small">${service.error_rate}%</span>
                            </div>
                            <div class="service-metric">
                                <span class="metric-label">版本:</span>
                                <span class="metric-value-small">v${service.version}</span>
                            </div>
                        </div>
                    </div>
                `;
            }).join('');
        }

        // 获取状态文本
        function getStatusText(status) {
            const statusMap = {
                'healthy': '健康',
                'warning': '警告',
                'error': '错误',
                'unknown': '未知'
            };
            return statusMap[status] || '未知';
        }

        // 获取运行时间徽章
        function getUptimeBadge(uptime) {
            if (uptime >= 99.5) {
                return { class: 'uptime-excellent', text: '优秀' };
            } else if (uptime >= 99.0) {
                return { class: 'uptime-good', text: '良好' };
            } else {
                return { class: 'uptime-poor', text: '较差' };
            }
        }

        // 更新整体状态
        function updateOverallStatus() {
            const hasError = mockServices.some(s => s.status === 'error');
            const hasWarning = mockServices.some(s => s.status === 'warning');
            
            const statusElement = document.getElementById('overall-status');
            const textElement = document.getElementById('status-text');
            const descElement = document.getElementById('status-description');

            if (hasError) {
                statusElement.textContent = '❌';
                statusElement.className = 'overall-status status-error';
                textElement.textContent = '系统存在问题';
                descElement.textContent = '部分服务出现错误，需要关注';
            } else if (hasWarning) {
                statusElement.textContent = '⚠️';
                statusElement.className = 'overall-status status-warning';
                textElement.textContent = '系统运行正常';
                descElement.textContent = '部分服务存在警告，建议检查';
            } else {
                statusElement.textContent = '✅';
                statusElement.className = 'overall-status status-healthy';
                textElement.textContent = '系统运行正常';
                descElement.textContent = '所有核心服务正常运行';
            }

            // 更新时间戳
            document.getElementById('last-update').textContent = 
                `最后更新时间: ${new Date().toLocaleString()}`;
        }

        // 显示加载状态
        function showLoading() {
            document.getElementById('services-container').innerHTML = 
                '<div class="loading">正在检查服务状态...</div>';
        }

        // 显示错误
        function showError(message) {
            const errorContainer = document.getElementById('error-container');
            errorContainer.innerHTML = `<div class="error-message">❌ ${message}</div>`;
        }

        // 隐藏错误
        function hideError() {
            document.getElementById('error-container').innerHTML = '';
        }

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', () => {
            loadHealthData();
            
            // 设置自动刷新（每20秒）
            setInterval(loadHealthData, 20000);
        });
    </script>
</body>
</html>